package stack;

import java.util.Stack;

public class StackSort<T extends Comparable<T>> {

    private Stack<T> stack;

    private Stack<T> help;

    public StackSort() {
        this.stack = new Stack<>();
        this.help = new Stack<>();
    }

    public synchronized void add(T t) {
        this.stack.push(t);
    }

    public synchronized void sort() {

        if (this.stack.isEmpty()) {
            return;
        }

        if (this.help.isEmpty()) {
            this.help.push(this.stack.pop());
        }

        while (!this.stack.isEmpty()) {

            this.insertBySort(this.stack.pop());
        }


        Stack<T> temp = this.help;
        this.help = this.stack;
        this.stack = temp;

    }


    private void insertBySort(T t) {

        T pop = this.help.pop();

        if (pop.compareTo(t) > 0) {
            if (this.help.isEmpty()) {
                this.help.push(t);
            } else {
                insertBySort(t);
            }
            this.help.push(pop);
            return;
        } else {
            this.help.push(pop);
        }

        this.help.push(t);
    }

    public synchronized Stack<T> getStack() {
        return this.stack;
    }
}
